工作後才知道的後端30件小事
可以先思考一下以下的輸出的什麼?
<?php
$arr = [
null,
0,
1,
2,
3,
'',
[],
[1, 2, 3]
];
foreach ($arr as $value) {
switch ($value) {
case null:
dump('this is null');
break;
case 0:
dump('this is 0');
break;
case 1:
dump('this is 1');
break;
case 2:
dump('this is 2');
break;
case 3:
dump('this is 3');
break;
case '':
dump('this is empty string');
break;
case []:
dump('this is []');
break;
case [1, 2, 3]:
dump('this is [1, 2, 3]');
break;
}
}
輸出:
"this is null"
"this is null"
"this is 1"
"this is 2"
"this is 3"
"this is null"
"this is null"
"this is [1, 2, 3]"
可以發現居然有 4 個 null!原因是什麼呢?
因為 switch 是 loose comparison,也就是==
,而非===
。
所以到第一個 case 時,$value == null
為真時就會進去;而在 PHP,null
、0
、''
、[]
跟null
都為真,跟empty()
有點像。
loose comparison 的相反是 strict comparsion
答案是不行,但有一些 tricky 的做法。
in_array()
預設也是 loose comparsion,但可以透過輸入參數去讓他做 strict comparsion!
// loose comparsion
in_array($value, $arr);
// strict comparsion
in_array($value, $arr, true);